<template>
  <div>
    <h1>Orderbook</h1>
    <h2>Bids</h2>
    <ul>
      <li v-for="(bid, index) in bids" :key="index">{{ bid.price }} - {{ bid.size }}</li>
    </ul>
    <h2>Asks</h2>
    <ul>
      <li v-for="(ask, index) in asks" :key="index">{{ ask.price }} - {{ ask.size }}</li>
    </ul>
  </div>
</template>

<script>
// 一定要确保安装了 serum 和 web3.js 相关的 npm 包
import { Account, Connection, PublicKey } from '@solana/web3.js';
import { Market } from '@project-serum/serum';
import { Buffer } from 'buffer';
window.Buffer = Buffer; // 可选，将Buffer挂载到全局对象上，使其在全局范围内可用

export default {
  name: 'SerumTrade',
  data() {
    return {
      connection: null,
      marketAddress: new PublicKey('2AdaV97p6SfkuMQJdu8DHhBhmJe7oWdvbm52MJfYQmfA'), // Provide the actual market address
      programAddress: new PublicKey("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX"), // Provide the Serum DEX program address   mainnet:srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX、Devnet：EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj
      market: null,
      bids: [],
      asks: [],
      // owner and payer are placeholders; you'll need to replace them accordingly
      owner: new Account(new Uint8Array([76, 66, 243, 229, 13, 156, 210, 31, 146, 224, 217, 0, 252, 42, 109, 41, 233, 155, 24, 178, 17, 206, 63, 144, 4, 166, 53, 86, 17, 96, 229, 107, 21, 214, 178, 46, 105, 253, 14, 151, 153, 60, 95, 11, 38, 124, 180, 19, 245, 56, 157, 185, 250, 224, 255, 31, 49, 205, 8, 229, 107, 223, 80, 80])), // This needs to be replaced with a real account
      payer: new PublicKey('55thTSxRPgMTQCuh4DMKvG7brimCnRmN5LjamP772kz1'), // This needs to be replaced with a real SPL token account
      price: 0
    };
  },
  methods: {
    async loadOrderbooks() {
      let bids = await this.market.loadBids(this.connection);
      let asks = await this.market.loadAsks(this.connection);
      this.bids = bids.getL2(20).map(([price, size]) => ({ price, size }));
      this.asks = [...asks].map(order => ({
        orderId: order.orderId.toString(),
        price: order.price,
        size: order.size,
        side: order.side,
      }));

      // 确保市场已加载
      if (!this.market) {
        console.error('Market not loaded');
        return;
      }
      // 创建下单指令
      console.log("===============")
      const topBid = this.bids.length > 0 ? this.bids[0].price : null;
      console.log("==============="+topBid)
      if (topBid) {
        const yourBidPrice = topBid; // 设置您的买入价为当前最高买价
      const yourBidSize = 100; // 这里设置您想要买入的数量
        try {
          await this.market.placeOrder(this.connection, {
            owner: this.owner,
            payer: this.payer,
            side: 'buy', // 'buy' 或 'sell'
            price: yourBidPrice,
            size: yourBidSize,
            orderType: 'limit', // 'limit' 或 'market'
          });
        } catch (error) {
          console.error("Error placing order:", error);
        }
      }
    },
    // ------------------------------------下单

  },

  async created() {
    this.connection = new Connection(`https://cool-restless-mountain.solana-mainnet.quiknode.pro/98008f695e9525faae315c31d7399d114bfd92a0/`);
    this.market = await Market.load(this.connection, this.marketAddress, {}, this.programAddress);
    await this.loadOrderbooks();
  },

};

</script>
